package com.ljh.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljh.mapper.EmployeeMapper;
import com.ljh.mapper.MailLogMapper;
import com.ljh.pojo.Employee;
import com.ljh.pojo.MailLog;
import com.ljh.service.IEmployeeService;
import com.ljh.utils.RespBean;
import com.ljh.vo.MailConstants;
import com.ljh.vo.RespPageBean;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lijiahao
 * @since 2021-09-01
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    /**
     * 查询员工（分页）
     * @param page
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RespPageBean findPageEmp(Integer page, Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页
        Page<Employee> employeePage = new Page<>(page,size);
        IPage<Employee> pageEmp = employeeMapper.findPageEmp(employeePage, employee, beginDateScope);
        RespPageBean respPageBean = new RespPageBean(pageEmp.getTotal(),pageEmp.getRecords());
        return respPageBean;
    }

    /**
     * 获取工号
     * @return
     */
    @Override
    public RespBean getMaxWorkId() {
//        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
//        return RespBean.success(null, String.format("%08d",Integer.parseInt(maps.get(0).get("max(workID").toString())+1));
        //随机生成15位工号
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<14;i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return RespBean.success(null,sb.toString());
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    @Transactional
    public RespBean addEmp(Employee employee) {
        //处理日期
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
        if (employeeMapper.insert(employee)==1){
            //如果数据库添加成功将消息放入消息队列，用于发邮件
            Employee emp = employeeMapper.exportListEmp(employee.getId()).get(0);
            //将消息落库rabbitmq
            //消息id
            //String msgId = UUID.randomUUID().toString();
            String msgId = "123";
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(MailConstants.DELIVERING);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME
            ,emp,new CorrelationData(msgId));
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    /**
     * 导出员工数据
     * @param id
     * @return
     */
    @Override
    public List<Employee> exportListEmp(Integer id) {
        return   employeeMapper.exportListEmp(id);

    }

    /**
     * 查询员工账套
     * @param page
     * @param size
     * @return
     */
    @Override
    public RespPageBean findListSalarySobCfg(Integer page, Integer size) {
        //开启分页
        Page<Employee> Page = new Page<>(page, size);
        IPage<Employee> iPage = employeeMapper.findListSalarySobCfg(Page);
        RespPageBean respPageBean = new RespPageBean(iPage.getTotal(),iPage.getRecords());
        return respPageBean;
    }
}
